; mouse.asm
; Mouse cursor handling
;

	.include "common.inc"
	.include "cursor.inc"
	.include "window.inc"
	.include "timer.inc"

	.export init_mouse
	.export do_mouse
	.export upd_mouse
	.export move_mouse
	.export click_mouse
	.export mouse_irq
	.export mousex
	.export mousey
	.export set_mouse_handler
	.export move_event

	.segment "JMPTABLE"

mouse_handler:	.word default_handler

	.segment "DATA"

new_mousex:		.byte $00
new_mousey:		.byte $00
new_mbutton:	.byte $00
mouse_event:	.tag MouseEvent

	mousex = mouse_event+MouseEvent::mx
	mousey = mouse_event+MouseEvent::my
	mbutton = mouse_event+MouseEvent::btn

	.segment "CODE"
	
init_mouse:	jsr cur_init
			; center on screen & show
			ldx #MAX_WIDTH/2
			ldy #MAX_HEIGHT/2
			stx new_mousex
			sty new_mousey
			stx mousex
			sty mousey
show_mouse:	jsr cur_move_to
			jmp cur_show

upd_mouse:	; calc delta
			sec
			lda new_mousex
			sbc mousex
			sta mouse_event+MouseEvent::dx
			lda #0
			sbc #0
			sta mouse_event+MouseEvent::dx+1
			sec
			lda new_mousey
			sbc mousey
			sta mouse_event+MouseEvent::dy
			lda #0
			sbc #0
			sta mouse_event+MouseEvent::dy+1
			lda mouse_event+MouseEvent::dx
			ora mouse_event+MouseEvent::dy
			beq @no_move
			; move mouse
			jsr cur_hide
			sei
			ldx new_mousex
			ldy new_mousey
			stx mousex
			sty mousey
			cli
			jsr show_mouse
			clc
			rts
@no_move:	sec
			rts

move_event:	; set event
			lda #EVT_MOUSE_MOVE
			sta mouse_event+Event::type
			jmp mset_event
	
do_mouse:	jsr upd_mouse
			bcs @do_click
			jsr move_event
@do_click:	lda mbutton
			eor new_mbutton
			beq @no_click
			ldx #EVT_MOUSE_DOWN
			lda new_mbutton
			bne @btn_dn
			inx
@btn_dn:	sta mbutton
			txa
			sta mouse_event+Event::type
			jsr mset_event	
@no_click:	rts

mset_event:	lda #<mouse_event
			ldx #>mouse_event
			jmp win_event
	
move_mouse:	stx new_mousex
			sty new_mousey
click_mouse:
			sta new_mbutton
			cmp mbutton
			bne @donotify
			cpx mousex
			bne @donotify
			cpy mousey
			bne @donotify
			rts

@donotify:	jmp notify_activity
	
mouse_irq:	jmp (mouse_handler)

set_mouse_handler:
			sei
			sta	mouse_handler
			stx mouse_handler+1
			cli 
			rts

default_handler:
			rts

	